const glob = require("glob");
const fs = require("fs");
const path = require("path");
const inquirer = require("inquirer");
const { dirOperaTypeChoices } = require("../config");
const removeDir = require("./delDir");
const ora = require("ora");
const t = require("../config/dict");
const { log } = require("../lib/utils");

module.exports = (context) => {
  if (context !== ".") {
    try {
      let projectName = context.name;
      console.log("");
      log("tip", {
        message: [
          "2)",
          t(context.lang, "创建项目"),
          projectName,
          t(context.lang, "目录"),
          t(context.lang, "。"),
        ].join(" "),
      });

      const findDirExist = (context, dirName, existHandle, noExistHandle) => {
        const list = glob.sync("*"); // 遍历当前目录
        if (list.length) {
          if (
            list.filter((name) => {
              const fileName = path.resolve(
                process.cwd(),
                path.join(".", name)
              );
              const isDir = fs.statSync(fileName).isDirectory(); // 使用同步函数 statSync，不使用异步函数stat
              const bool = name === dirName && isDir;
              return bool;
            }).length !== 0
          ) {
            return existHandle(context);
          }
        }
        return noExistHandle(context);
      };

      const reNameHandle = (context) => {
        return inquirer
          .prompt([
            {
              name: "projectDir",
              message: [t(context.lang, "新目录命名"), "?"].join(""),
              default: context.metadata.projectDir,
            },
          ])
          .then((answers) => {
            return findDirExist(
              context,
              answers.projectDir,
              () => {
                log("error", {
                  message: [
                    t(context.lang, "需要重新命名"),
                    t(context.lang, "。"),
                  ].join(" "),
                });
                return reNameHandle(context);
              },
              () => {
                context.metadata.projectDir = answers.projectDir;
                log("success", {
                  message: [
                    t(context.lang, "完成，新目录命名并创建目录") + ",",
                    context.metadata.projectDir,
                    t(context.lang, "。"),
                  ].join(" "),
                });
                console.log("");
                return context;
              }
            );
          });
      };

      const mkDir = (context) => {
        return removeDir("*", context.metadata.projectDir, context)
          .then(() => {
            const spinner = ora(
              t(context.lang, "创建项目") +
                " " +
                t(context.lang, "目录") +
                "\\" +
                context.name +
                " ..."
            );
            spinner.start();
            try {
              fs.mkdirSync(context.metadata.projectDir);
              spinner.succeed();
              console.log("");
              return context;
            } catch (err) {
              spinner.fail();
              return Promise.reject(err);
            }
          })
          .catch((err) => {
            return Promise.reject(err);
          });
      };

      const done = (context) => {
        return findDirExist(
          context,
          context.metadata.projectDir,
          (context) => {
            if (
              process.env.FORCEOVERWRITE === "true" ||
              (context.metadata.projectMode &&
                context.metadata.projectMode === "auto")
            ) {
              log("warn", {
                message:
                  t(context.lang, "强制覆盖已有目录(如果存在)") +
                  t(context.lang, "。"),
              });
              return mkDir(context);
            } else {
              log("warn", {
                message:
                  t(context.lang, "建议重命名, 覆盖可能会导致错误") +
                  t(context.lang, "。"),
              });
              return inquirer
                .prompt([
                  {
                    name: "projectDirOperaType",
                    message: [
                      t(context.lang, "这个项目"),
                      projectName,
                      t(context.lang, "目录已经存在，如何处理"),
                      "?",
                    ].join(" "),
                    default: "overwrite",
                    pageSize: 4,
                    type: "rawlist",
                    choices: [
                      ...t(context.lang, dirOperaTypeChoices),
                      {
                        name: t(context.lang, "取消"),
                        value: "cancel",
                      },
                    ],
                  },
                ])
                .then((answers) => {
                  switch (answers.projectDirOperaType) {
                    case "overwrite":
                      return mkDir(context);
                    case "rename":
                      return reNameHandle(context);
                    default:
                      return Promise.reject({
                        message:
                          t(context.lang, "用户取消") + t(context.lang, "。"),
                      });
                  }
                })
                .catch((err) => {
                  return Promise.reject(err);
                });
            }
          },
          (context) => {
            fs.mkdirSync(context.metadata.projectDir);
            log("success", {
              message: t(context.lang, "完成") + t(context.lang, "。"),
            });
            console.log("");
            return context;
          }
        );
      };

      return done(context);
    } catch (err) {
      return Promise.reject(err);
    }
  } else {
    return Promise.reject({
      message: t(context.lang, "未知错误") + t(context.lang, "。"),
    });
  }
};
